#include <windows.h>		// Header File For Windows
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

#define DEST_PORT 80
#define BUFSIZE 1000

char buffer[BUFSIZE];

void parseHTML()
{	
	//parse anything after img src ending with "
	

}

char* getIP(char* hostname)
{
	hostent* ht;
	if ((ht=gethostbyname(hostname)) == NULL)
	{
		herror("gethostbyname failed");
		exit(1);
    }
	return(ht->h_addr);
}

int main(int argc, char **argv)
{
	int sockfd;
	char* host = argv[1];
    struct sockaddr_in dest_addr;   // will hold the destination addr
	
    sockfd = socket(PF_INET, SOCK_STREAM, 0); // do some error checking!

    dest_addr.sin_family = AF_INET;          // host byte order
    dest_addr.sin_port = htons(DEST_PORT);   // short, network byte order
    dest_addr.sin_addr = *((struct in_addr *)(getIP(host)));
    //dest_addr.sin_addr.s_addr = inet_addr(DEST_IP);

	memset(dest_addr.sin_zero, '\0', sizeof dest_addr.sin_zero);

    if(connect(sockfd, (struct sockaddr *)&dest_addr, sizeof dest_addr) == -1)
	{
		perror("connect error");
        exit(1);
    }

	FILE* offsoc;
	FILE* tosoc;
	ofstream HTML("HTML.txt");
    
	//Try to connect to socket
	if((offsoc = fdopen(sockfd, "r")) == NULL)
	{
       perror("Could not open file stream on supplied file descriptor");
       exit(1);
    }
	if((tosoc = fdopen(sockfd, "w")) == NULL)
	{
       perror("Could not open file stream on supplied file descriptor");
       exit(1);
    }
	//Get data
	fprintf(tosoc, "GET / HTTP/1.0\n\n"); //mymessage is the get request
	fflush(tosoc);

	char *s = fgets(buffer, BUFSIZE-1, offsoc);
	for(int i = 1; s != NULL; i++)
	{
		printf("%s", buffer);
		HTML << buffer;
		s = fgets(buffer, BUFSIZE-1, offsoc);
	}
	
	//close connections
	fclose(offsoc);
	fclose(tosoc);
	close(sockfd);
	HTML.close();

    return 0;
}
